<template>
  <div v-if="options" ref="SelectBoxRef" class="select_container">
    <!-- 多选标签展示区域 -->
    <div ref="tagsContainer" class="tags_container" v-if="selectedItems.length > 0">
        <span v-for="(item, index) in selectedItems" class="tag">
          {{ item[labelKey] }}
          <span @click.stop="removeTag(index)" class="tag-close">×</span>
        </span>
    </div>
    <!--输入框区域-->
    <div @click="isShopOptions = !isShopOptions" class="input_area">
      <!-- 输入框 -->
      <input
        @focus="inputFocus"
        @input="filterOptions()"
        :class="selectedItems.length > 0 ? 'font_placeholder font_value' : 'font_placeholder'"
        v-model="searchText"
        :placeholder="placeholder"
      />
      <!--右边的箭头-->
      <div class="arrow right_icon">
        <img src="@/assets/home-img/arrow_down.png" alt=""/>
      </div>
    </div>

    <!--选项数组-->
    <div v-if="isShopOptions" class="items">
      <div
        @click="toggleItem(item)"
        v-for="item in optionsValueArr"
        :class="isSelected(item) ? 'item_s item' : 'item'"
      >
        {{ item[labelKey] }}
        <span v-if="isSelected(item)" class="check-mark">✓</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, reactive, watch} from "vue";
import {defineModel, onMounted, onBeforeUnmount} from 'vue'


defineOptions({
  name: "MultiSelect",
  inheritAttrs: false,
});

const props = defineProps({
  // select的选项
  options: {
    type: Array,
    default: null,
  },
  // select的选项显示值字段
  labelKey: {
    type: String,
    default: "label",
  },
  // select的选项实际值字段
  valueKey: {
    type: String,
    default: "value",
  },
  // 占位符
  placeholder: {
    type: String,
    default: "请选择"
  },
  // 最大选择数量
  maxSelect: {
    type: Number,
    default: null
  }
});

// 与父组件绑定值
const modelValue = defineModel()

console.log(modelValue.value)
const optionsValueArr = ref([]) // 组件内部实际显示的options
const selectedItems = ref([]) // 当前选中的项数组
const isShopOptions = ref(false) // 是否展示选项列表
const searchText = ref("") // 输入框绑定值

// 检查项是否已选中
function isSelected(item) {
  return selectedItems.value.some(selected => selected[props.valueKey] === item[props.valueKey]);
}

const tagsContainer = ref(null)

function scrollToRight() {
  nextTick(() => {
    if (tagsContainer.value) {
      tagsContainer.value.scrollTo({
        left: tagsContainer.value.scrollWidth,
        behavior: 'smooth'
      });
    }
  });
}

// 切换选项选择状态
function toggleItem(item) {
  console.log(item, selectedItems.value)
  if (isSelected(item)) {
    // 如果已选中，则移除
    selectedItems.value = selectedItems.value.filter(
      selected => selected[props.valueKey] !== item[props.valueKey]
    );
  } else {
    // 如果未选中，则添加（检查是否超过最大选择数量）
    if (props.maxSelect && selectedItems.value.length >= props.maxSelect) {
      return;
    }
    selectedItems.value.push(item);

    scrollToRight()
  }

  //更新value值
  modelValue.value = selectedItems.value.map(item => item[props.valueKey]);

  console.log(modelValue.value,"modelValue.value")
}

// 移除标签
function removeTag(index) {
  selectedItems.value.splice(index, 1);

  //更新value值
  modelValue.value = selectedItems.value.map(item => item[props.valueKey]);
}


// 点击空白处关闭选择弹框
const handleDocumentClick = (event) => {
  if (SelectBoxRef && !SelectBoxRef.value.contains(event.target)) {
    isShopOptions.value = false;
    resetFilter();
  }
};

// 整个select组件区域
const SelectBoxRef = ref(null);

// 过滤筛选项
function filterOptions() {
  if (!searchText.value) {
    optionsValueArr.value = props.options;
    return;
  }
  optionsValueArr.value = props.options.filter(option => {
    return option[props.labelKey].toLowerCase().includes(searchText.value.toLowerCase());
  });
}

// input框聚焦时清空searchText
function inputFocus() {
  console.log("聚焦")
  searchText.value = "";
  optionsValueArr.value = props.options;
}

// 重置过滤
function resetFilter() {
  optionsValueArr.value = props.options;
  searchText.value = "";
}


// 监听options变化
watch(() => props.options, (newVal) => {
  if (newVal) {
    optionsValueArr.value = newVal;
  }
}, {immediate: true});

watch(
  () => modelValue.value,
  (newValue) => {
    // 与父组件绑定值
//从options数组中根据对应的value找到对应值 设置当前选中项selectedItems
// 使用 filter 方法 (适用于可能有多个匹配项)
// modelValue为[1,2,3]
    if(modelValue.value){
      let valueArr = modelValue.value.split(',');
      console.log(optionsValueArr.value,"valueArr")
      const currentItems = optionsValueArr.value.filter(item =>{
        console.log(item[props.valueKey],"item[props.valueKey]")
        return valueArr.includes(item[props.valueKey])
        console.log(item[props.valueKey],"item[props.valueKey]")
      });
      console.log(currentItems,"currentItems")
      selectedItems.value = currentItems;
    }
  }
)

onMounted(() => {
  document.addEventListener('click', handleDocumentClick);
});

onBeforeUnmount(() => {
  document.removeEventListener('click', handleDocumentClick);
});
</script>

<style lang="scss" scoped>
.select_container {
  position: relative;
  width: 100%;
  height: 100%;
  background: #F0F2F7;
  padding: 0px 12px;
  border-radius: 8px;
  box-sizing: border-box;
  display: flex;
}

.input_area {
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-wrap: wrap;
  gap: 6px;
  min-height: 24px;
  flex: 1;

  input {
    width: 100%;
    flex: 1;
    border: none;
    outline: none;
    background: none;
    box-shadow: none;
    margin: 0;
    color: inherit;
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;
  }
}


.tags_container {
  max-width: 50%; /* 固定宽度，可根据需要调整 */
  overflow-x: auto; /* 横向滚动 */
  overflow-y: hidden; /* 隐藏纵向滚动 */
  flex-shrink: 0; /* 防止容器被压缩 */
  scrollbar-width: thin; /* 细滚动条 */
  scrollbar-color: #ccc #f5f5f5; /* 滚动条颜色 */
  display: flex;
  flex-wrap: nowrap;
  gap: 4px;
  padding: 4px;
  box-sizing: border-box;

  /* Webkit浏览器滚动条样式 */
  &::-webkit-scrollbar {
    height: 4px;
  }

  &::-webkit-scrollbar-track {
    background: #f5f5f5;
    border-radius: 2px;
  }

  &::-webkit-scrollbar-thumb {
    background: #ccc;
    border-radius: 2px;
  }

  &::-webkit-scrollbar-thumb:hover {
    background: #aaa;
  }
}

.tags_scroll {
  display: inline-flex; /* 内联flex布局使内容不换行 */
  gap: 4px;
  padding-bottom: 2px; /* 为滚动条留出空间 */
  min-width: 100%; /* 确保内容宽度足够 */
}

.tag {
  background: #E6F9F5;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  color: #1e90ff;
  display: inline-flex; /* 改为inline-flex */
  align-items: center;
  white-space: nowrap; /* 防止标签内文字换行 */
  flex-shrink: 0; /* 防止标签被压缩 */
  border: 1px solid #fff;

  .tag-close {
    margin-left: 4px;
    cursor: pointer;
    font-size: 14px;
    color: #808690;

    &:hover {
      color: #ff4d4f;
    }
  }
}


.tag {
  background: #E6F9F5;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  color: #1e90ff;
  display: flex;
  align-items: center;

  .tag-close {
    margin-left: 4px;
    cursor: pointer;
    font-size: 14px;
    color: #808690;

    &:hover {
      color: #ff4d4f;
    }
  }
}

.right_icon {
  width: 16px;
  height: 16px;
  transition: all 0.6s;
  flex-shrink: 0;

  img {
    width: 100%;
    height: 100%;
  }
}

.font_placeholder {
  font-size: 14px;
  font-weight: normal;
  line-height: 20px;
  letter-spacing: normal;
  color: #808690;
}

.font_value {
  color: #1C1E24;
}



.items {
  width: 100%;
  position: absolute;
  z-index: 20;
  left: 0;
  top: 105%;
  border-radius: 4px;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
  color: #808690;
  padding: 4px 4px;
  max-height: 250px;
  overflow-y: auto;

  .item {
    padding: 8px 12px;
    font-size: 14px;
    font-weight: normal;
    line-height: 20px;
    letter-spacing: normal;
    color: #808690;
    display: flex;
    justify-content: space-between;
    align-items: center;
    cursor: pointer;

    &:hover {
      background-color: #f5f5f5;
    }
  }

  .item_s {
    border-radius: 8px;
    background: #E6F9F5;
    font-weight: bold;
    color: #1e90ff;
  }

  .check-mark {
    font-weight: bold;
  }
}
</style>
